package com.sgb.kjwl.viewmodel.home;

import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.model.entity.home.CityEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.view.ui.activity.home.ChoiceCityActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.util.PinyinUtil;

import java.util.ArrayList;
import java.util.List;

public class ChoiceCityModel extends BaseViewModel {
    private HomeRepertory repertory;
    private ChoiceCityActivity activity;

    public ChoiceCityModel(ChoiceCityActivity activity, HomeRepertory repertory) {
        this.activity = activity;
        this.repertory = repertory;
    }

    public String getCityName() {
        return repertory.getAreaName();
    }

    public String getCityCode() {
        return repertory.getAreaCode();
    }

    public void setCity(CityEntity cityEntity) {
        String cityName = cityEntity.getCityName();
        if (cityEntity.getCityName().contains("市")) {
            cityName = cityEntity.getCityName().substring(0, cityEntity.getCityName().length()-1);
        }

        repertory.setAreaName(cityName);
        repertory.setAreaCode(cityEntity.getCityCode());
    }

    /**
     * 获取城市列表数据
     */
    public void getCityList() {
        APIManager.getInstance().getCommonAPI().getCityList().enqueue(new ICallBack<BaseEntity<List<CityEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CityEntity>> data) {
                activity.setCityDatas(data.getData());
            }
        });
    }

    /**
     * 搜索列表数据匹配
     * @param entityList
     * @param condition
     */
    public void searchFilterModel(List<CityEntity> entityList, String condition) {
        if (entityList == null) {
            return;
        }
        List<CityEntity> filterList = new ArrayList<>();
        if (condition.equals("")) {
            activity.setSearchCitys(entityList);
            return;
        }
        for (CityEntity entity : entityList) {
            String name = entity.getCityName();
            String pinyin = PinyinUtil.chineneToSpell(name);
            if (pinyin.contains(condition) || name.contains(condition)) {
                filterList.add(entity);
            }
        }
        activity.setSearchCitys(filterList);
    }

}
